import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import {
  Row, Col, Card, Form, Input, Radio, Select, Icon, Button, Upload, message, InputNumber, Checkbox
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Goods.less';
import { imgPrex } from '../../utils/constData'

import { routerRedux } from 'dva/router';
import TextArea from 'antd/lib/input/TextArea';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const { Option } = Select;
const CheckboxGroup = Checkbox.Group;
const options = [
  { label: '全积分', value: '1' },
  { label: '积分', value: '2' },
];

const formItemLayout = { labelCol: { span: 2 }, wrapperCol: { span: 15 } }

const priceItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 8 } }
const priceItemLayout1 = { labelCol: { span: 2 }, wrapperCol: { span: 22 } }

const tailFormItemLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 16, offset: 2 },
  },
};


@connect(({ goods, loading }) => ({
  goods,
  categoryList: goods.categoryList,
  loading: loading.models.goods,
}))
@Form.create()
export default class EditGoods extends PureComponent {
  state = {
    record: null,
    fileList: [],
    file: null,
    image: null,

    showImgUrlList: [],

    priceType1: true,
    priceType2: false,
  };

  componentDidMount() {
    if (this.props.match.params.goodsId != 'new') {
      this.props.dispatch({
        type: 'goods/fetchGoodsDetail',
        payload: { goodsId: this.props.match.params.goodsId },
        callback: (data) => this._setBackData(data)
      });
    }

    this.props.dispatch({
      type: 'goods/fetchCategoryList',
    });
  }

  _setBackData(data) {
    let backUrl = [];
    if (data && data.goodsShowImgList && (data.goodsShowImgList.length > 0)) {
      for (let i = 0; i < data.goodsShowImgList.length; i++) {
        let one = data.goodsShowImgList[i];
        let newOne = {}
        newOne['uid'] = one.showId;
        newOne['name'] = '轮播图' + i;
        newOne['status'] = 'done';
        newOne['url'] = one.showImgUrl;
        backUrl.push(newOne)
      }
    }
    this.setState({
      record: data, showImgUrlList: backUrl,
      priceType1: ((data.priceType == "1") || (data.priceType == "3")),
      priceType2: ((data.priceType == "2") || (data.priceType == "3"))
    })
  }

  checkOriginalPrice = (rule, value, callback) => {
    const { getFieldValue } = this.props.form
    if (value && value < getFieldValue('discountPrice')) {
      callback('原价不能小于售价！')
    }

    // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
    callback()
  }

  uploadShowImg(option) {
    console.log(option)
    this.props.dispatch({
      type: 'goods/addImage',
      payload: option.file,
      callback: (data) => this._uploadCallback(data)
    });
  }

  showBeforeUpload(file) {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片大小不能超过1M');
      return false;
    }

    return true;
  }

  _uploadCallback(data) {
    let showImgUrlList = this.state.showImgUrlList;
    let index = 1;
    if (showImgUrlList && (showImgUrlList.length > 0)) {
      index = showImgUrlList.length + 1
    }
    let newOne = {};
    newOne['uid'] = index;
    newOne['name'] = '轮播图' + index;
    newOne['status'] = 'done';
    newOne['url'] = imgPrex + data;
    showImgUrlList.push(newOne)
  }

  _remove(file) {
    console.log(file)
    let newList = this.state.showImgUrlList.filter(item => item.url != file.url);
    this.setState({ showImgUrlList: newList })
  }

  normFile = (e) => {
    const isLt1M = e.file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      this.setState({ fileList: [], file: null })
      return (this.state.record && this.state.record.goodsImg) ? this.state.record.goodsImg : null;
    }

    if (e.fileList && e.fileList.length > 0) {
      return e && e.file;
    } else {
      return null;
    }
  }

  showNormFile = (e) => {
    const isLt1M = e.file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      return null;
    }
  }



  submit() {
    console.log('this.props.form=====', this.props.form.getFieldsValue())
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (!(this.state.showImgUrlList && this.state.showImgUrlList.length > 0)) {
        message.error('请选择轮播图')
        return;
      }

      if (!this.state.priceType1 && !this.state.priceType2) {
        message.error('请至少勾选一种兑换方式')
        return;
      }

      console.log('表单提交图片：：：：？？？', this.state.file)
      let priceType = null;

      if (this.state.priceType1 && this.state.priceType2) {
        priceType = 3;
      } else if (this.state.priceType1) {
        priceType = 1;
        if (fieldsValue.goodsScore) {

        } else {
          fieldsValue.goodsScore = 0;
        }
        // fieldsValue.goodsCash = 0;
        // delete fieldsValue.goodsScore;
        // delete fieldsValue.goodsCash;
      } else if (this.state.priceType2) {
        priceType = 2;
        if (fieldsValue.goodsScoreAll) {

        } else {
          fieldsValue.goodsScoreAll = 0;
        }
      }


      let showImgUrlList = [];
      if (this.state.showImgUrlList && (this.state.showImgUrlList.length > 0)) {
        for (let i = 0; i < this.state.showImgUrlList.length; i++) {
          let one = {}
          one['showImgUrl'] = this.state.showImgUrlList[i].url;
          showImgUrlList.push(one)
        }
      }

      let values = { ...fieldsValue, name: this.state.file, showImgUrlList: showImgUrlList, priceType: priceType }
      console.log('表单提交数据：：：：？？？', values)

      if (values.goodsId) {
        this.props.dispatch({
          type: 'goods/editGoods',
          payload: values,
          callback: () => this._callback()
        });
      } else {
        this.props.dispatch({
          type: 'goods/addGoods',
          payload: values,
          callback: () => this._callback()
        });
      }


    });
  }

  _callback() {
    this.props.dispatch(routerRedux.goBack())
  }

  onChange(type, e) {
    if (type == "1") {
      this.setState({ priceType1: e.target.checked })
    }
    if (type == "2") {
      this.setState({ priceType2: e.target.checked })
    }
  }


  render() {
    const { form } = this.props;
    const { record, bookletFormVisible } = this.state;
    console.log(record)
    const uploadProps = {
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
            file: null,
          };
        });
        this.props.form.setFieldsValue({ name: (record && record.goodsImg) ? record.goodsImg : null })
      },
      beforeUpload: (file) => {
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (!isLt1M) {
          message.error('图片大小不能超过1M');
          return false;
        }
        this.setState(({ fileList }) => ({
          fileList: [file],
          file: file,
          image: null,
        }));
        this.props.form.setFieldsValue({
          name: file
        });
        return false;
      },
      fileList: this.state.fileList
    };

    const showImgUrlListUploadProps = {
      // action: '//jsonplaceholder.typicode.com/posts/',
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            bookletFileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          bookletFileList: [file],
          bookletFile: file,
          bookletImage: null,
        }));

        return false;
      },
      fileList: this.state.bookletFileList
    };

    return (
      <PageHeaderLayout title="">
        <Card>
          <Form  >
            {record ?
              <FormItem {...formItemLayout} label="id" style={{ display: 'none' }}>
                {form.getFieldDecorator('goodsId', {
                  rules: [{ required: true, message: '请输入id' }],
                  initialValue: record ? '' + record.goodsId : null,
                })(<Input placeholder="请输入id" />)}
              </FormItem>
              :
              null
            }

            <FormItem {...formItemLayout} label="类目">
              {form.getFieldDecorator('catId', {
                rules: [{ required: true, message: '请选择类目' }],
                initialValue: record ? record.catId : null,
              })(
                <Select style={{ width: '60%' }}>
                  <Option value={null}>请选择</Option>
                  {(this.props.goods.categoryList && this.props.goods.categoryList.length > 0) && this.props.goods.categoryList.map((item, i) => <Option key={i} value={'' + item.catId}>{item.catName}</Option>)}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="缩略图">
              {
                form.getFieldDecorator('name', {
                  valuePropName: 'file',
                  getValueFromEvent: this.normFile,
                  rules: [{ required: true, message: '缩略图不能为空' }],
                  initialValue: record ? record.goodsImg : null,
                })
                  (<Upload
                    {...uploadProps}
                  >
                    <Button>
                      <Icon type="upload" />浏览
         			  </Button>
                  </Upload>)}
              {(record && record.goodsImg && !(this.state.fileList && (this.state.fileList.length > 0))) ?
                <img src={imgPrex + record.goodsImg} style={{ width: 50 }} />
                :
                null
              }
            </FormItem>

            <FormItem {...formItemLayout} label="轮播图">
              {form.getFieldDecorator('showImgUrlList', {
                rules: [{ required: true, message: '请选择轮播图' }],
                initialValue: record ? record.goodsShowImgList : null,
              })(
                <Upload
                  customRequest={(options) => this.uploadShowImg(options)}
                  listType="picture-card"
                  fileList={this.state.showImgUrlList}
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}
                  beforeUpload={(file) => this.showBeforeUpload(file)}
                  onRemove={(file) => this._remove(file)}
                >
                  {this.state.showImgUrlList.length >= 5 ? null :
                    <div>
                      <Icon type="plus" />
                      <div className="ant-upload-text">上传</div>
                    </div>
                  }
                </Upload>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="名称">
              {form.getFieldDecorator('goodsName', {
                initialValue: record ? record.goodsName : null,
                rules: [{
                  required: true, message: '名称不能为空且不能包含特殊字符',
                  pattern: /^[A-Za-z0-9\u4e00-\u9fa5]*$/
                }]
              })(<Input placeholder="请输入名称" maxLength={10} />)}
            </FormItem>

            <Row>
              <Col span={24}>
                <div style={{ display: 'flex', }}>
                  <div style={{ display: 'flex', marginTop: '10px', marginLeft: '30px' }}>
                    <div style={{ display: 'flex', marginTop: '10px', }}>
                      <span style={{ color: 'red' }}>*</span> 价格
                        <Checkbox style={{ marginLeft: '10px' }} checked={this.state.priceType1} onChange={(e) => this.onChange(1, e)}>全积分</Checkbox>
                    </div>
                    <FormItem {...priceItemLayout1} label="">
                      {form.getFieldDecorator('goodsScoreAll',
                        this.state.priceType1 ?
                          {
                            rules: [{ required: true, message: '请输入积分' }],
                            initialValue: (record && record.goodsScoreAll) ? record.goodsScoreAll : null,
                          }
                          :
                          {
                            initialValue: (record && record.goodsScoreAll) ? record.goodsScoreAll : null,
                          }
                      )(
                        <InputNumber min={0} step={1} precision={0} max={999999} />
                      )}
                    </FormItem>
                  </div>

                  <div style={{ display: 'flex', marginTop: '10px', marginLeft: '30px' }}>
                    <div style={{ display: 'flex', marginTop: '10px', marginLeft: '30px' }}>
                      <Checkbox style={{ marginLeft: '10px' }} checked={this.state.priceType2} onChange={(e) => this.onChange(2, e)} >积分</Checkbox>
                    </div>
                    <FormItem {...priceItemLayout1} label="">
                      {form.getFieldDecorator('goodsScore',
                        this.state.priceType2 ?
                          {
                            rules: [{ required: true, message: '请输入积分' }],
                            initialValue: (record && record.goodsScore) ? record.goodsScore : null,
                          }
                          :
                          {
                            initialValue: (record && record.goodsScore) ? record.goodsScore : null,
                          }
                      )(
                        <InputNumber min={0} step={1} precision={0} max={999999} />
                      )}
                    </FormItem>
                    <span style={{ marginTop: '10px' }}> +现金 </span>
                    <FormItem {...priceItemLayout1} label="">
                      {form.getFieldDecorator('goodsCash',
                        this.state.priceType2 ?
                          {
                            rules: [{ required: true, message: '请输入现金' }],
                            initialValue: record ? record.goodsCash : null,
                          }
                          :
                          {
                            initialValue: record ? record.goodsCash : null,
                          }
                      )(
                        <InputNumber min={1} step={1} max={999999} precision={2} />
                      )}
                    </FormItem>
                  </div>
                </div>
              </Col>
            </Row>

            {
              record ? null :
                <FormItem {...formItemLayout} label="状态">
                  {form.getFieldDecorator('goodsSts', {
                    rules: [{ required: true, message: '请选择商品状态' }],
                    initialValue: record ? record.goodsSts ? record.goodsSts : "1" : "1",
                  })(
                    <RadioGroup>
                      <RadioButton value="1">上架</RadioButton>
                      <RadioButton value="2">下架</RadioButton>
                    </RadioGroup>
                  )}
                </FormItem>
            }


            <FormItem {...formItemLayout} label="权重">
              {form.getFieldDecorator('weight', {
                rules: [{ required: true, message: '请输入权重' }],
                initialValue: record ? record.weight : 1000,
              })(<InputNumber min={0} max={999999} step={1} precision={0} placeholder="请输入权重" style={{ width: '50%' }} />)}
            </FormItem>

            <FormItem {...formItemLayout} label="邮费">
              {form.getFieldDecorator('goodsPostg', {
                rules: [{ required: true, message: '请输入邮费' }],
                initialValue: record ? record.goodsPostg : null,
              })(<InputNumber min={0} max={999999} step={1} precision={0} placeholder="请输入邮费" style={{ width: '50%' }} />)}
            </FormItem>

            <FormItem {...formItemLayout} label="商品介绍">
              {form.getFieldDecorator('goodsIntr', {
                rules: [{ required: true, message: '请输入商品介绍' }],
                initialValue: record ? record.goodsIntr : null,
              })(<TextArea cols={4} placeholder="请输入商品介绍" maxLength={1000} />)}
            </FormItem>

            <FormItem {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit" onClick={() => this.submit()} loading={this.props.loading}>
                保存
              </Button>
              <Button type="danger" onClick={() => { this.props.dispatch(routerRedux.goBack()) }} style={{ marginLeft: '15px' }}>
                返回列表
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout >
    );
  }

}
